from django import forms
from .models import comment, articles
from Login import models


class CreationModelForm(forms.ModelForm):
    substrings = ['tmd', 'fuck', '傻逼']  # 存放敏感词

    class Meta:
        model = articles  # 数据表
        # 为了更方便所以将user_id放进表单中，这样save时可以一并保存进数据库
        fields = ["user_id", "articles_title", "articles_content", "articles_label", "articles_host"]

    def clean_user_id(self):
        """检测是否存在用户"""
        user_id = self.cleaned_data.get('user_id')  # 从前端取数据
        if models.User.objects.filter(user_id=user_id).exists():
            return user_id
        raise forms.ValidationError("用户不存在")

    def clean_articles_title(self):
        """标题"""
        title_msg = self.cleaned_data.get("articles_title")
        for substring in self.substrings:
            if substring in title_msg:
                raise forms.ValidationError(f"请对文章进行修改，不要使用敏感词:{substring}！！！")
        return title_msg

    def clean_articles_content(self):
        """文本"""
        content_msg = self.cleaned_data.get("articles_content")
        for substring in self.substrings:
            if substring in content_msg:
                raise forms.ValidationError(f"请对文章进行修改，不要使用敏感词:{substring}！！！")
        return content_msg

    def clean_articles_label(self):
        """文章标签"""
        label_msg = self.cleaned_data.get("articles_label")
        for substring in self.substrings:
            if substring in label_msg:
                raise forms.ValidationError(f"请对文章进行修改，不要使用敏感词:{substring}！！！")
        return label_msg
